import 'package:hive/hive.dart';
import 'package:uuid/uuid.dart';
import '../models/chat_model.dart';
import '../models/message_model.dart';
import '../services/user_service.dart'; // Added import for UserService

class ChatService {
  final Box<ChatModel> _chatBox = Hive.box<ChatModel>('chats');
  final Box<MessageModel> _messageBox = Hive.box<MessageModel>('messages');
  final Uuid _uuid = Uuid();

  // 创建聊天
  Future<ChatModel> createChat({
    required List<String> participantIds,
    bool isGroupChat = false,
    String? groupName,
    String? groupAvatar,
  }) async {
    final chatId = _uuid.v4();
    final chat = ChatModel(
      id: chatId,
      participantIds: participantIds,
      isGroupChat: isGroupChat,
      lastMessageTime: DateTime.now(),
      groupName: groupName,
      groupAvatar: groupAvatar,
    );

    await _chatBox.put(chat.id, chat);
    return chat;
  }

  // 获取聊天
  ChatModel? getChatById(String id) {
    return _chatBox.get(id);
  }

  // 更新聊天
  Future<void> updateChat(ChatModel chat) async {
    await _chatBox.put(chat.id, chat);
  }

  // 删除聊天
  Future<void> deleteChat(String id) async {
    // 删除相关的所有消息
    final messages = getMessagesByChat(id);
    for (var message in messages) {
      await _messageBox.delete(message.id);
    }
    await _chatBox.delete(id);
  }

  // 获取用户的所有聊天
  List<ChatModel> getUserChats(String userId) {
    return _chatBox.values
        .where((chat) => chat.participantIds.contains(userId))
        .toList()
      ..sort((a, b) => b.lastMessageTime.compareTo(a.lastMessageTime));
  }

  // 获取用户的群聊
  List<ChatModel> getUserGroupChats(String userId) {
    return _chatBox.values
        .where(
          (chat) => chat.participantIds.contains(userId) && chat.isGroupChat,
        )
        .toList()
      ..sort((a, b) => b.lastMessageTime.compareTo(a.lastMessageTime));
  }

  // 获取用户的单聊
  List<ChatModel> getUserPrivateChats(String userId) {
    return _chatBox.values
        .where(
          (chat) => chat.participantIds.contains(userId) && !chat.isGroupChat,
        )
        .toList()
      ..sort((a, b) => b.lastMessageTime.compareTo(a.lastMessageTime));
  }

  // 发送消息
  Future<MessageModel> sendMessage({
    required String chatId,
    required String senderId,
    required String content,
    bool isEmoji = false,
    String? emojiPath,
    bool isTeamInvite = false,
    String? teamId,
  }) async {
    final message = MessageModel(
      id: _uuid.v4(),
      chatId: chatId,
      senderId: senderId,
      content: content,
      isEmoji: isEmoji,
      emojiPath: emojiPath,
      isTeamInvite: isTeamInvite,
      teamId: teamId,
      sentAt: DateTime.now(),
    );

    await _messageBox.put(message.id, message);

    // 更新聊天的最后一条消息和时间
    final chat = getChatById(chatId);
    if (chat != null) {
      chat.updateLastMessage(message.id, message.sentAt);

      // 为除发送者外的所有参与者分别加未读
      for (var participantId in chat.participantIds) {
        if (participantId != senderId) {
          chat.incrementUnreadCount(participantId);
        }
      }
      await updateChat(chat);
    }

    return message;
  }

  // 获取聊天的消息
  List<MessageModel> getMessagesByChat(String chatId) {
    return _messageBox.values
        .where((message) => message.chatId == chatId)
        .toList()
      ..sort((a, b) => a.sentAt.compareTo(b.sentAt)); // 按时间升序排序
  }

  // 标记消息为已读
  Future<void> markMessagesAsRead(String chatId, String userId) async {
    final chat = getChatById(chatId);
    if (chat != null && chat.participantIds.contains(userId)) {
      // 只清零当前用户的未读数
      chat.resetUnreadCount(userId);
      await updateChat(chat);

      // 标记所有消息为已读
      final messages = getMessagesByChat(chatId);
      for (var message in messages) {
        if (!message.isRead && message.senderId != userId) {
          message.markAsRead();
          await _messageBox.put(message.id, message);
        }
      }
    }
  }

  // 查找或创建两个用户之间的私聊
  Future<ChatModel> findOrCreatePrivateChat(
    String userId1,
    String userId2,
  ) async {
    // 先查找现有的私聊
    try {
      final existingChat = _chatBox.values.firstWhere(
        (chat) =>
            !chat.isGroupChat &&
            chat.participantIds.length == 2 &&
            chat.participantIds.contains(userId1) &&
            chat.participantIds.contains(userId2),
      );
      return existingChat;
    } catch (e) {
      // 未找到私聊，创建新的
      return await createChat(
        participantIds: [userId1, userId2],
        isGroupChat: false,
      );
    }
  }

  // 添加样例聊天和消息数据（开发测试用）
  Future<void> createSampleChatsAndMessages(List<String> userIds) async {
    if (_chatBox.isEmpty && userIds.isNotEmpty) {
      // Ezra的userId
      final userService = UserService();
      final ezra = userService.getUserByUsername('lalala');
      if (ezra == null) return;
      final ezraId = ezra.id;
      // Ezra与其他所有用户建立单聊
      for (int i = 0; i < userIds.length; i++) {
        final otherId = userIds[i];
        if (otherId == ezraId) continue;
        final privateChat = await createChat(
          participantIds: [ezraId, otherId],
          isGroupChat: false,
        );
        // 生成不同的消息内容和时间
        final now = DateTime.now().subtract(Duration(minutes: i * 7));
        final ezraMsg =
            [
              'Hi, this is Ezra. How are you?',
              'Hey! Long time no see.',
              'Hello! Ready for the next dive?',
              'Hi there! Did you finish your project?',
              'Hey, want to join the team event?',
              'Good morning! How was your weekend?',
              'Hi! Any new underwater photos?',
              'Hey, let me know if you need help.',
              'Hello! Are you coming to the meeting?',
              'Hi! Let’s catch up soon!',
            ][i % 10];
        final replyMsg =
            [
              'Hi Ezra! I am good, thanks!',
              'Yes, let’s meet up soon.',
              'Absolutely, can’t wait!',
              'Yes, just submitted it yesterday.',
              'Sounds fun, count me in!',
              'Weekend was great, thanks!',
              'Yes, I’ll send you some.',
              'Thanks Ezra, appreciate it!',
              'Yes, see you there!',
              'Sure, let’s do it!',
            ][i % 10];
        await sendMessage(
          chatId: privateChat.id,
          senderId: ezraId,
          content: ezraMsg,
        );
        await Future.delayed(Duration(milliseconds: 100));
        await sendMessage(
          chatId: privateChat.id,
          senderId: otherId,
          content: replyMsg,
        );
        // 修改消息时间（模拟历史消息）
        final messages = getMessagesByChat(privateChat.id);
        if (messages.length >= 2) {
          messages[messages.length - 2].sentAt = now;
          messages[messages.length - 1].sentAt = now.add(Duration(minutes: 2));
          await _messageBox.put(
            messages[messages.length - 2].id,
            messages[messages.length - 2],
          );
          await _messageBox.put(
            messages[messages.length - 1].id,
            messages[messages.length - 1],
          );
        }
      }
      // 其余群聊等逻辑可保留或按需调整
      // 创建私聊2: 用户1和用户3之间的聊天
      final privateChat2 = await createChat(
        participantIds: [userIds[0], userIds[2]],
        isGroupChat: false,
      );

      // 添加消息到私聊2
      await sendMessage(
        chatId: privateChat2.id,
        senderId: userIds[2],
        content:
            'I saw your underwater photos from your last dive. They\'re amazing!',
      );

      await sendMessage(
        chatId: privateChat2.id,
        senderId: userIds[0],
        content:
            'Thanks! I\'ve been practicing a lot with the new camera settings.',
      );

      await sendMessage(
        chatId: privateChat2.id,
        senderId: userIds[2],
        content:
            'Would you mind sharing your camera settings? I\'m struggling with the lighting underwater.',
      );

      // 创建群聊1: 潜水团队群聊
      final groupChat1 = await createChat(
        participantIds: [userIds[0], userIds[1], userIds[2], userIds[3]],
        isGroupChat: true,
        groupName: 'Coral Reef Divers',
        groupAvatar: 'assets/images/touxiang1.png',
      );

      // 添加消息到群聊1
      await sendMessage(
        chatId: groupChat1.id,
        senderId: userIds[0],
        content: 'Welcome everyone to our diving team chat!',
      );

      await sendMessage(
        chatId: groupChat1.id,
        senderId: userIds[3],
        content:
            'Thanks for organizing this trip. What\'s the dive plan for the first day?',
      );

      await sendMessage(
        chatId: groupChat1.id,
        senderId: userIds[1],
        content:
            'We\'ll start with a shallow reef dive in the morning, followed by lunch, and then a deeper dive in the afternoon.',
      );

      await sendMessage(
        chatId: groupChat1.id,
        senderId: userIds[2],
        content:
            'Sounds perfect! What\'s the water temperature expected to be?',
      );

      await sendMessage(
        chatId: groupChat1.id,
        senderId: userIds[0],
        content: 'Around 25°C (77°F). A 3mm wetsuit should be comfortable.',
      );

      // 创建群聊2: 海洋保护活动群聊
      final groupChat2 = await createChat(
        participantIds: [userIds[0], userIds[2], userIds[4]],
        isGroupChat: true,
        groupName: 'Ocean Cleanup Volunteers',
        groupAvatar: 'assets/images/touxiang5.png',
      );

      // 添加消息到群聊2
      await sendMessage(
        chatId: groupChat2.id,
        senderId: userIds[4],
        content:
            'Our next beach cleanup is scheduled for Saturday morning at 8am.',
      );

      await sendMessage(
        chatId: groupChat2.id,
        senderId: userIds[0],
        content: 'I\'ll be there! Should I bring extra trash bags?',
      );

      await sendMessage(
        chatId: groupChat2.id,
        senderId: userIds[4],
        content:
            'Yes please, and don\'t forget gloves. We\'ll provide refreshments.',
      );

      await sendMessage(
        chatId: groupChat2.id,
        senderId: userIds[2],
        content:
            'I\'ll bring my data collection sheets so we can track what we find for the marine debris database.',
      );

      // 发送表情消息
      await sendMessage(
        chatId: groupChat2.id,
        senderId: userIds[0],
        content: 'assets/images/good.png',
        isEmoji: true,
        emojiPath: 'assets/images/good.png',
      );
    }
  }
}
